package com.ruoyi.enterprise.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.RegisterAndLoginMessage;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.extra.EPhone;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.random.RandomUtil;
import com.ruoyi.enterprise.service.PhoneService;
import com.ruoyi.system.mapper.SysUserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * description: 短信服务Controller
 * @author: gql
 * @date: 2022/08
 */
@RestController
@RequestMapping("/sms")
public class PhoneController {

    @Autowired
    private PhoneService smsService;

    /**
     * RedisTemplate
     */
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper userMapper;


    /**
     * 获取短信验证码
     * @param phone 手机号
     * @return 发送验证码到phone
     * getSmsCode: 注册验证码       getSmsCode/login 登录验证码
     */
    @GetMapping(value = {"getSmsCode/{phone}", "getSmsCode/login/{phone}"})
    public AjaxResult getSmsCode(@PathVariable("phone") String phone, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        // 登录接口
        if (requestURI.contains("login")) { // 登录
            SysUser user = userMapper.selectUserByPhone(phone);
            if (ObjectUtils.isEmpty(user)) {
                return AjaxResult.error(RegisterAndLoginMessage.MSG_8);
            }
        } else { //注册
            SysUser user = userMapper.selectUserByPhone(phone);
            if (!ObjectUtils.isEmpty(user)) {
                return AjaxResult.error(RegisterAndLoginMessage.MSG_9);
            }
        }


        // 短信有效期3分钟
        if (redisCache.getCacheObject(phone) == null) {
            String code = RandomUtil.getFourBitRandom();
            Map<String, Object> map = new HashMap<>(16);
            map.put("mobile", phone);
            map.put("code", code);
            boolean flag;
            try {
                flag = this.smsService.sendMessage(phone, code);
            } catch (Exception e) {
                return AjaxResult.error();
            }
            if (flag) {
                // 发送成功,Redis中存储3分钟
                redisCache.setCacheObject(phone, map, 3, TimeUnit.MINUTES);
                return AjaxResult.success(RegisterAndLoginMessage.MSG_2 + phone);
            } else {
                return AjaxResult.error();
            }
        } else {
            return AjaxResult.error(RegisterAndLoginMessage.MSG_3);
        }
    }

    @PostMapping("/login")
    public AjaxResult phoneLogin(@RequestBody EPhone ePhone){
        SysUser sysUser = userMapper.selectUserByPhone(ePhone.getPhone());
        if ( sysUser == null){
            return AjaxResult.error(RegisterAndLoginMessage.MSG_8);
        }
        if (!ePhone.getCode().equals(redisCache.getCacheObject(ePhone.getPhone()))){
            return AjaxResult.error(RegisterAndLoginMessage.MSG_5);
        }

        return null;
    }
}
